<?php

namespace App\Handlers;

use Illuminate\Support\Facades\Cache;

class WeconHandler
{
    // protected static $alias = '18350050969';
    protected static $alias = 'meigexing';
    // protected static $password = 'S43130403';
    protected static $password = '19880110';
    protected static $comid = "192";
    protected static $compvtkey = '28bb2d44023145b29a79d5595b85f63e';
    protected static $screctkey = 'f1cd9351930d4e589922edbcf3b09a7c';

    protected static $onlineDomain = 'yun.xmcitypower.com';

    public static function getSid(){
        $nowDomain = env('APP_URL');
        if (strpos($nowDomain, self::$onlineDomain)) {    //上线
            $cacheKey = 'wecon_sid';
            $sid = Cache::get($cacheKey);
            if ($sid) {
                return $sid;
            } else {
                $sid = self::login();
                Cache::put($cacheKey, $sid);
                return $sid;
            }
        } else {    //本地到线上取
            $apiUrl = 'http://'.self::$onlineDomain.'/api/getWeikongSid';
            $res = file_get_contents($apiUrl);
            $r = json_decode($res, true);
            if (!empty($r['code'])) {
                return $r['sid'];
            }
            return false;
        }
    }

    public static function login(){
        $url = 'http://api.v-box.net/box-data/api/we-data/login';
        $time = time();
        $params = [
            'alias' => self::$alias,
            'password' => md5(self::$password),
            'ts' => $time,
        ];        


        $sign = self::genSign($params);

        $common = [
            'sign' => $sign,
            'ts' => $time
        ];

        $res = self::_curl($url, $common, ['alias' => self::$alias, 'password' => md5(self::$password)]);
        if ($res) {
            return $res['sid'];
        }
    }

    protected static function genSign($params){
        $fixation = [
            'comid' => self::$comid,
            'compvtkey' => self::$compvtkey,
        ];
        $arr = array_merge($fixation, $params);
        ksort($arr);

        $str = '';
        foreach ($arr as $key => $value) {
            $str .= "&" . $key . "=" . $value;
        }
        $str = substr($str, 1); 
        $str .= '&key='.self::$screctkey;       
        return md5($str);
    }

    /**
     * [getBoxList 盒子列表（新，多级分组）]
     * @return [type] [description]
     */
    public static function getBoxList(){
        $url = 'http://api.v-box.net/box-data/api/we-data/boxlist';
        $res = self::getCurlRes($url);
        if ($res) {
            return $res['list'];
        } else {
            return false;
        }
    }

    public static function getBoxIdByMachineCode($machineCode){
        $boxId = 0;
        $list = self::getBoxList();
        if ($list) {
            foreach ($list as $groups) {
                foreach ($groups['boxList'] as $oneBox) {
                    if ($oneBox['machineCode'] == $machineCode) {
                        $boxId = $oneBox['boxId'];
                        break;
                    }
                }
            }
        }
        return $boxId;
    }

    /**
     * [getRealtimeGroups 实时监控点分组列表]
     * @return [type] [description]
     */
    public static function getRealtimeGroups($boxId){
        $url = 'http://api.v-box.net/box-data/api/we-data/realgroups';
        $data['boxId'] = $boxId;    //21490;
        $res = self::getCurlRes($url, $data);
        if ($res) {
            return $res['list'];
        }
    }

    /**
     * [xxx 实时监控点配置列表]
     * @return [type] [description]
     */
    public static function getConfigList($boxId, $groupId){
        $url = 'http://api.v-box.net/box-data/api/we-data/realcfgs';
        $data['boxId'] = $boxId;
        $data['groupId'] = $groupId;
        $data['pageSize'] = 50;
        $data['pageIndex'] = 1;
        $res = self::getCurlRes($url, $data);
        if ($res) {
            return $res['cfgList'];
        }
    }

    public static function getRealtimeData($boxId, $groupId){
        $url = 'http://api.v-box.net/box-data/api/we-data/realdata';
        $data['boxId'] = $boxId;   //21490;
        $data['groupId'] = $groupId; //133640;
        $data['pageSize'] = 50;
        $data['pageIndex'] = 1;
        $res = self::getCurlRes($url, $data);
        if ($res) {
            return $res['list'];
        }
    }

    public static function getMonitorData(){
        $url = 'http://api.v-box.net/box-data/api/we-data/monitors';
        $data['boxId'] = 21490;
        $res = self::getCurlRes($url, $data);
    }

    public static function getHistorydataData(){
        $url = 'http://api.v-box.net/box-data/api/we-data/historydata';
        $data['monitorId'] = 1192346;
        $data['monitorBeginTime'] = strtotime("-365 day");
        $data['monitorEndTime'] = time();
        $data['pageSize'] = 10;
        $data['pageIndex'] = 1;
        $res = self::getCurlRes($url, $data);
    }

    public static function getBoxStatus($machineCode){
        $url = 'http://api.v-box.net/box-data/api/we-data/getDeviceState';
        $data['machineCode'] = $machineCode;
        $res = self::getCurlRes($url, $data);
        if ($res) {
            if (isset($res['state'])) {
                return $res['state'];
            } else {
                return 0;
            }
        }
    }

    protected static function getCurlRes($url, $data = []){
        $time = time();
        $sid = self::getSid();
        $params['sid'] = $sid;
        $params['ts'] = $time;
        $sign = self::genSign(array_merge($params, $data));
        $params['sign'] = $sign;
        $res = self::_curl($url, $params, $data);
        return $res;
    }

    public static function genPostParam($data){
        $fixation = [
            'comid' => self::$comid,
            'compvtkey' => self::$compvtkey,
        ];

        $time = time();
        $sid = self::getSid();
        $params['sid'] = $sid;
        $params['ts'] = $time;
        $sign = self::genSign(array_merge($params, $data));
        $params['sign'] = $sign;
        $arr = array_merge($fixation, $params);

        $header = [
            'Content-type' => 'application/x-www-form-urlencoded',
            'common' => json_encode($arr)
        ];

        return ['header' => $header, 'data' => $data];
    }

    public static function sendNotice($boxId){
        $url = 'http://api.v-box.net/box-data/api/we-data/sendSwitchToDevice';
        $data['boxId'] = $boxId;//21490;
        $res = self::getCurlRes($url, $data);
    }

    public static function setData($monitorId, $value)
    {
        $url = 'http://api.v-box.net/box-data/api/we-data/updrealdata';
        $data['monitorId'] = $monitorId;
        $data['value'] = $value;
        $res = self::getCurlRes($url, $data);
        return $res;
    }

    protected static function _curl($url, $common, $data = []){
        $fixation = [
            'comid' => self::$comid,
            'compvtkey' => self::$compvtkey,
        ];
        $arr = array_merge($fixation, $common);
        $header = [
            'Content-type: application/x-www-form-urlencoded',
            'common:'.json_encode($arr)
        ];
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        // curl_setopt($ch, CURLOPT_POST, 1);
        if (!empty($data)) {
            $data = http_build_query($data);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        $output = curl_exec($ch);
        curl_close($ch);
        $res = json_decode($output,true);
        if ($res['code'] == 200 && $res['msg'] == 'ok') {
            return $res['result'];
        } else {
            if ($res['code'] == 403) {
                $cacheKey = 'wecon_sid';
                Cache::forget($cacheKey);
            }
            return false;
        }
    }
}